import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:crypto/crypto.dart';

extension ValidateString on String {
  /// 规范换行字符
  /// 以兼容手动编辑的不规范内容
  String get validateNewLine => replaceAll(r'\\n', '\n').replaceAll('/n', '\n');
}

extension StringExtension on String {
  /// 计算字符串的文字长度
  /// 使用了特殊的计算方式:
  /// 对于ascII字符，记为一个
  /// 其它字符，记为2个
  int calcLength() {
    if (isEmpty) {
      return 0;
    }
    int ret = 0;
    for (int i = 0; i < length; i++) {
      int part = codeUnitAt(i);
      if (part >= 0 && part <= 255) {
        ret += 1;
      } else {
        ret += 2;
      }
    }
    return ret;
  }

  /// 截取字符串, 考虑ascII字符和其它字符的长度
  String substr(int length) {
    var sb = "";
    var currentLength = 0;
    for (int i = 0; i < this.length; i++) {
      var c = this[i].toString();
      currentLength += c.calcLength();
      if (currentLength <= length) {
        sb += c;
      } else {
        break;
      }
    }
    return sb;
  }

  Color get color {
    if (startsWith("#") && (length == 7 || length == 9)) {
      String res;
      if (length == 7) {
        res = replaceAll("#", "0xFF");
      } else {
        res = replaceAll("#", "0x");
      }
      return Color(int.tryParse(res) ?? 0);
    } else {
      return Colors.white;
    }
  }

  String toMd5() {
    return md5.convert(utf8.encode(this)).toString();
  }

  // Future toast({int? showTimeLength}) =>
  //     // print("获取原生端数据用户为占卜师 debug");
  //     Fluttertoast.showToast(
  //         msg: this,
  //         toastLength: Toast.LENGTH_SHORT,
  //         gravity: ToastGravity.BOTTOM,
  //         timeInSecForIosWeb: showTimeLength ?? 2, // 显示2秒
  //         backgroundColor: Colors.black87,
  //         textColor: Colors.white,
  //         fontSize: 16.sp);
}
